//
//  NewsAlbumViewController.m
//  suRead
//
//  Created by lidi on 15/11/8.
//  Copyright © 2015年 bao. All rights reserved.
//

#import "NewsAlbumViewController.h"
#import "Masonry.h"
#import "ServiceNews.h"
#import "ShareService.h"
#import "UIControl+Blocks.h"
#import "UIViewController+HUD.h"
#import "PhotoImageView.h"
#import "FMDBHelpers.h"

#import "M_NewsDetail.h"

#import "NewsCommentViewController.h"
#import "AnalyticsManager.h"
#import "AccountManager.h"
#import "ServiceUserNew.h"
#import "LoginViewController.h"

@interface NewsAlbumViewController ()<UIScrollViewDelegate>
@property (nonatomic,strong) UIScrollView *albumScrollView;

@property (nonatomic,strong) NSArray *imagesArray;
@property (nonatomic,strong) NSMutableArray *photoImageViewsHandle;

@property (nonatomic,strong) UIView *topBarView;
@property (nonatomic,strong) UIView *bottomBarView;
@property (nonatomic,strong) UIView *bottomContentView;

@property (nonatomic,strong) UILabel *labelTitle;
@property (nonatomic,strong) UITextView *labelContent;
@property (nonatomic,strong) UILabel *labelIndex;

@property (nonatomic,assign) BOOL isTopAndBottomBarShow;

@property (nonatomic,strong) M_NewsDetail *newsDetail;

//@property (nonatomic,strong) UILabel *labelCommentCount;
//@property (nonatomic,strong) UIButton *buttonPraise;

//统计
@property(nonatomic,strong)NSString *targetId;
@property(nonatomic,strong)NSString *targetUrl;

@end

@implementation NewsAlbumViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.targetId && [self.targetId length] > 0) {
        [AnalyticsManager event:AnalyticsEventType_comeIn targetId:self.targetId url:self.targetUrl];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.targetId && [self.targetId length] > 0) {
        [AnalyticsManager event:AnalyticsEventType_leave targetId:self.targetId url:self.targetUrl];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _isTopAndBottomBarShow = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    [self initViews];
    [self refreshData];
}

- (void)initViews
{
    __weak typeof(self) weak_self = self;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setNeedsStatusBarAppearanceUpdate];
    
    //图片
    self.albumScrollView = [UIScrollView new];
    self.albumScrollView.delegate = self;
    self.albumScrollView.backgroundColor = [UIColor blackColor];
    self.albumScrollView.pagingEnabled = YES;
    
    [self.view addSubview:self.albumScrollView];
    [self.albumScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weak_self.albumScrollView.superview).insets(UIEdgeInsetsZero);
    }];

    //底部
    self.bottomContentView = [UIView new];
    [self.view addSubview:self.bottomContentView];
    [self.bottomContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(15.0f);
        make.right.equalTo(self.view).offset(-15.0f);
        make.bottom.equalTo(self.view).offset(-49.0f);
        make.height.equalTo(@135.0f);
    }];
    
    self.labelIndex = [UILabel new];
    self.labelIndex.textColor = [UIColor whiteColor];
    self.labelIndex.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:13.0f];
    [self.bottomContentView addSubview:self.labelIndex];
    [self.labelIndex mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.equalTo(self.bottomContentView);
    }];
    [self.labelIndex setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    [self.labelIndex setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    
    self.labelContent = [UITextView new];
    self.labelContent.editable = NO;
    self.labelContent.backgroundColor = [UIColor clearColor];
    self.labelContent.textColor = [UIColor whiteColor];
    self.labelContent.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:15.0f];
    [self.bottomContentView addSubview:self.labelContent];
    [self.labelContent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bottomContentView);
        make.right.equalTo(self.labelIndex.mas_left).with.offset(-10.0f);
        make.top.equalTo(self.bottomContentView);
        make.bottom.equalTo(self.bottomContentView).with.offset(-10.0f);
    }];
    
    self.bottomBarView = [UIView new];
    self.bottomBarView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.bottomBarView];
    [self.bottomBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weak_self.view);
        make.top.equalTo(self.bottomBarView.superview);
        if (iPhoneX) {
            make.height.equalTo(@88.0f);
        } else {
            make.height.equalTo(@64.0f);
        }
    }];
    
    UIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonBack setImage:[UIImage imageNamed:@"button_backward"] forState:UIControlStateNormal];
    [buttonBack addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        //返回
        [weak_self.navigationController popViewControllerAnimated:YES];
    }];
    
//    UIButton *buttonViewComment = [UIButton buttonWithType:UIButtonTypeCustom];
//    [buttonViewComment setImage: [UIImage imageNamed:@"btn_comments"] forState:UIControlStateNormal];
//    [buttonViewComment addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
//        //查看评论列表
//        NewsCommentViewController *newsCommentViewController = [NewsCommentViewController new];
//        newsCommentViewController.commentsUrl = weak_self.newsDetail.f_commentsUrl;
//        newsCommentViewController.commentId = weak_self.newsDetail.f_commentid;
//        newsCommentViewController.targetId = weak_self.targetId;
//        newsCommentViewController.targetUrl = weak_self.targetUrl;
//        [weak_self.navigationController pushViewController:newsCommentViewController animated:YES];
//    }];
//
//    self.buttonPraise = [UIButton buttonWithType:UIButtonTypeCustom];
//    [self.buttonPraise setImage:[UIImage imageNamed:@"btn_praise"] forState:UIControlStateNormal];
//    [self.buttonPraise addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
//
//         if (![AccountManager sharedAccountManager].f_isLogined) {
//             // 需要登录
//             UIStoryboard *personalCenterStoryBoard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
//             LoginViewController *controller = [personalCenterStoryBoard instantiateViewControllerWithIdentifier:@"LoginViewController"];
//             controller.hidesBottomBarWhenPushed = YES;
//             [weak_self.navigationController showViewController:controller sender:nil];
//             return;
//         }
//
//         if (![[FMDBHelpers sharedInstance] queryData:weak_self.newsDetail.f_docid type:0]) {
//
//             if (weak_self.targetId && [weak_self.targetId length] > 0) {
//                 [AnalyticsManager event:AnalyticsEventType_praise targetId:weak_self.targetId url:weak_self.targetUrl];
//             }
//
//             //赞
//             [weak_self showHUDProgress:@""];
//             [ServiceUserNew doLike:weak_self.newsDetail.f_docid success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
//                 [weak_self removeHUDProgress];
//                 [[FMDBHelpers sharedInstance] insertData:weak_self.newsDetail.f_docid andType:0];
//                 [weak_self.buttonPraise setImage:[UIImage imageNamed:@"btn_praised"] forState:UIControlStateNormal];
//             } failure:^(NSString * _Nonnull message) {
//                 [weak_self removeHUDProgress];
//                 [weak_self showHUDText:message];
//             }];
//         } else {
//             //取消点赞
//             [weak_self showHUDProgress:@""];
//             [ServiceUserNew doUnLike:weak_self.newsDetail.f_docid success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
//                 [weak_self removeHUDProgress];
//                 [[FMDBHelpers sharedInstance] deleteData:weak_self.newsDetail.f_docid type:0];
//                 [weak_self.buttonPraise setImage:[UIImage imageNamed:@"btn_praise"] forState:UIControlStateNormal];
//             } failure:^(NSString * _Nonnull message) {
//                 [weak_self removeHUDProgress];
//                 [weak_self showHUDText:message];
//             }];
//         }
//     }];
//
    UIButton *buttonShare = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonShare setImage:[UIImage imageNamed:@"icon_zb_share"] forState:UIControlStateNormal];
    [buttonShare addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        NSString *shareUrl_ = weak_self.newsDetail.f_source_url;
        if ([shareUrl_ rangeOfString:@"?"].location != NSNotFound)
        {
            shareUrl_ = [shareUrl_ stringByAppendingString:[NSString stringWithFormat:@"&uct=%@",[ServiceNews getAuthCode]]];
        }
        
        [ShareService share:weak_self url:shareUrl_ title:weak_self.newsDetail.f_title image:weak_self.newsDetail.f_thumbnail completion:^(id result, NSError *error) {
            
            if (weak_self.targetId && [weak_self.targetId length] > 0) {
                [AnalyticsManager event:AnalyticsEventType_forward targetId:weak_self.targetId url:weak_self.targetUrl];
            }
        }];
    }];
    
    UILabel *linelab = [UILabel new];
    linelab.backgroundColor = [UIColor colorWithRed:160/255.0f green:160/255.0f blue:160/255.0f alpha:1.0f];
    
    [self.bottomBarView addSubview:linelab];
    
    [self.bottomBarView addSubview:buttonBack];
//    [self.bottomBarView addSubview:buttonViewComment];
//    [self.bottomBarView addSubview:self.buttonPraise];
    [self.bottomBarView addSubview:buttonShare];
    
    [linelab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.bottomBarView);
        make.height.equalTo(@0.5f);
    }];
    
    [buttonBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weak_self.bottomBarView);
        make.left.equalTo(weak_self.bottomBarView).with.offset(8.0f);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@44.0f);
    }];
    
    [buttonShare mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weak_self.bottomBarView);
        make.right.equalTo(weak_self.bottomBarView).with.offset(-8.0f);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@44.0f);
    }];
//
//    [buttonViewComment mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.mas_equalTo(buttonShare.mas_left).with.offset(-8.0f);
//        make.bottom.equalTo(self.bottomBarView);
//        make.width.equalTo(@28.0f);
//        make.height.equalTo(@44.0f);
//    }];
//
//    [self.buttonPraise mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.mas_equalTo(buttonViewComment.mas_left).with.offset(-8.0f);
//        make.bottom.equalTo(self.bottomBarView);
//        make.width.equalTo(@28.0f);
//        make.height.equalTo(@44.0f);
//    }];
//
//    self.labelCommentCount = [UILabel new];
//    self.labelCommentCount.textAlignment = NSTextAlignmentCenter;
//    self.labelCommentCount.textColor = [UIColor whiteColor];
//    self.labelCommentCount.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:9.0f];
//    [self.bottomBarView addSubview:self.labelCommentCount];
//    [self refreshCommentLabelWith:@"0"];
    
    //头部
    self.topBarView = [UIView new];
    [self.view addSubview:self.topBarView];
    [self.topBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weak_self.topBarView.superview);
        make.top.equalTo(weak_self.bottomBarView.mas_bottom);
        make.height.equalTo(@44.0f);
    }];
    
    self.labelTitle = [UILabel new];
    self.labelTitle.textColor = [UIColor whiteColor];
    self.labelTitle.textAlignment = NSTextAlignmentCenter;
    self.labelTitle.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:18.0f];
    [self.topBarView addSubview:self.labelTitle];
    [self.labelTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.topBarView);
        make.left.right.equalTo(self.topBarView);
    }];
    [self.labelTitle setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
    [self.labelTitle setContentHuggingPriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
}

- (void)refreshData
{
    __weak typeof(self) weak_self = self;
    [self showHUDProgress:@""];
    [ServiceNews doFetchNewsDetail:self.urlString success:^(id responseObject, NSString *message) {
        [weak_self removeHUDProgress];
        M_NewsDetail *newsDetail = responseObject;
        weak_self.newsDetail = responseObject;
        
        // 统计
        weak_self.targetId = weak_self.newsDetail.f_docid;
        weak_self.targetUrl = weak_self.urlString;
        [AnalyticsManager event:AnalyticsEventType_comeIn targetId:weak_self.targetId url:weak_self.targetUrl];
        
//        if ([AccountManager sharedAccountManager].f_isLogined && [[FMDBHelpers sharedInstance] queryData:weak_self.newsDetail.f_docid type:0]) {
//            [weak_self.buttonPraise setImage:[UIImage imageNamed:@"btn_praised"] forState:UIControlStateNormal];
//        } else {
//            [weak_self.buttonPraise setImage:[UIImage imageNamed:@"btn_praise"] forState:UIControlStateNormal];
//        }

        [weak_self refreshCommentLabelWith:weak_self.newsDetail.f_comments];
        //添加图片
        weak_self.imagesArray = newsDetail.f_images;
        weak_self.photoImageViewsHandle = [NSMutableArray array];
        
        UIView *albumScrollViewContentView = [UIView new];
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        [weak_self.albumScrollView addSubview:albumScrollViewContentView];
        [albumScrollViewContentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(weak_self.albumScrollView).insets(UIEdgeInsetsZero);
            make.height.mas_equalTo(weak_self.albumScrollView.mas_height);
            make.width.equalTo(@(screenSize.width * [newsDetail.f_images count]));
        }];
        
        
        UIView *preView = nil;
        for (NSInteger i=0; i<[newsDetail.f_images count]; i++) {
            
            NSDictionary *newsPhotoDic = [newsDetail.f_images objectAtIndex:i];
            NSString *photoURL = [newsPhotoDic objectForKey:@"img"];
            
            UIScrollView *photoImageScrollView = [UIScrollView new];
            [albumScrollViewContentView addSubview:photoImageScrollView];
            [photoImageScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.equalTo(photoImageScrollView.superview);
                
                if (!preView) {
                    make.left.equalTo(photoImageScrollView.superview);
                }
                else {
                    make.left.equalTo(preView.mas_right);
                }
                
                make.width.equalTo(@(screenSize.width));
            }];
            preView = photoImageScrollView;
            
            PhotoImageView *photoImageView = [[PhotoImageView alloc] initWithURL:photoURL placeHolder:nil];
            photoImageView.photoImageViewTap = ^ {
                
                if (weak_self.isTopAndBottomBarShow) {
                    //隐藏
                    [UIView animateWithDuration:.3f animations:^{
                        weak_self.topBarView.alpha = 0;
                        weak_self.bottomContentView.alpha = 0;
                        weak_self.bottomBarView.alpha = 0;
                    } completion:^(BOOL finished) {
                        weak_self.isTopAndBottomBarShow = NO;
                    }];
                }
                else {
                    //显示
                    [UIView animateWithDuration:.3f animations:^{
                        weak_self.topBarView.alpha = 1;
                        weak_self.bottomContentView.alpha = 1;
                        weak_self.bottomBarView.alpha = 1;
                    } completion:^(BOOL finished) {
                        weak_self.isTopAndBottomBarShow = YES;
                    }];
                }
            };
            [photoImageScrollView addSubview:photoImageView];

            [photoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(photoImageView.superview);
                make.size.mas_equalTo(CGSizeMake(screenSize.width, screenSize.height));
            }];
            
            [self.photoImageViewsHandle addObject:photoImageView];
        }
        
        if ([newsDetail.f_images count]) {
            [self refreshTitleAtIndex:0];
        }
        
        
    } failure:^(NSString *message) {
        [weak_self removeHUDProgress];
        [weak_self showHUDText:message];
    }];
}

- (void)refreshTitleAtIndex:(NSInteger)index_
{
    NSDictionary *photoInfoDic = [self.imagesArray objectAtIndex:index_];
    self.labelTitle.text = [photoInfoDic objectForKey:@"title"];
    self.labelContent.text = [photoInfoDic objectForKey:@"descr"];
    self.labelIndex.text = [NSString stringWithFormat:@"%ld/%ld",index_ + 1 , [self.imagesArray count]];
}

- (void)refreshCommentLabelWith:(NSString *)commentCount
{
//    self.labelCommentCount.text = commentCount;
//
//    CGFloat width_ = [commentCount sizeWithAttributes:@{NSFontAttributeName:self.labelCommentCount.font}].width + 10.0f;
//    width_ = width_ < 25.0f ? 25.0f : width_;
//    CGFloat x_ = [UIScreen mainScreen].bounds.size.width - 58.0f - width_ / 2;
//
//    [self.labelCommentCount mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.labelCommentCount.superview).offset(28.0f);
//        make.left.equalTo(self.labelCommentCount.superview).offset(x_);
//        make.width.equalTo(@(width_));
//    }];
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    for (PhotoImageView *photoImageView in self.photoImageViewsHandle) {
        if (photoImageView.currentScale !=0 && photoImageView.currentScale != 1.0f) {
            [photoImageView resetScale];
        }
    }
    
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    NSInteger currentPage = floor((scrollView.contentOffset.x - screenWidth / 2) / screenWidth) + 1;
    [self refreshTitleAtIndex:currentPage];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
@end
